<?php

include_once './curl.class.php';
include_once './wx.class.php';
$menuList = include_once './menu.php';

$wx = new WX();
echo $wx->getAccessToken();

class WX
{
    private const TOKEN = 'weixin';
    private const APPID = 'wx04883371bbd10059';
    private const APPSECRET = 'd9712decdf49aabcea0c575f4e021ba0';

    public function __construct(){
        // 第一次进入才进行校验
        if(!empty($_GET['echostr'])){
            echo $this->checkSignature();exit;
        }else{
            $this->acceptMsg();
        }
    }

    /**
     *  接入检验
     *  @params token signature echostr
     */
    private function checkSignature(){
        $input = $_GET;
        $echostr  = $input['echostr'];
        $signature  = $input['signature'];
        unset($input['echostr'], $input['signature']);
        $input['token'] = self::TOKEN;
        $tmpStr = implode($input);
        $tmpStr = sha1($tmpStr);

        if($tmpStr === $signature){
            return $echostr;
        }

        return  '';
    }

    /**
     *  获取access_token
     */
    public function getAccessToken()
    {
        $surl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';
        $url = sprintf($surl, self::APPID, self::APPSECRET);

        $curl = new CURL();
        $json = $curl::curl_request($url);
        $accessTokenArr = json_decode($json, true);
        return $accessTokenArr['access_token'];
    }

    /**
     *  消息接收
     */
    public function acceptMsg()
    {   
        $WxAbility = new WxAbility();
        $WxAbility->MsgReply();
    }

    /**
     *  创建菜单
     */
    public function createMenu($menuList)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='. $this->getAccessToken();
        $curl = new CURL();
        $json = $curl::curl_request($url, json_encode($menuList, JSON_UNESCAPED_UNICODE));
        return $json;
    }
}